package com.example.udpDemo.utils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import io.netty.buffer.ByteBufUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

/**
 * Description:
 *
 * @author sjt Administrator
 * @since 2023/11/30 14:16
 */

@Slf4j
public class AESUtil {


    /**
     * 输出大写的16进制密文字符串
     *
     * @param key     密钥
     * @param content 加密内容
     * @return byte[]
     * @auther sjt Administrator
     * @since 2023/12/3 20:05
     */
    @SneakyThrows
    public static byte[] encrypt(String key, byte[] content) {
        byte[] bytes = dataSupplement(content);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        return cipher.doFinal(bytes);
    }

    /**
     * 解密
     *
     * @param key     密钥
     * @param content 解密内容
     * @return
     * @auther sjt Administrator
     * @since 2023/12/3 20:07
     */
    @SneakyThrows
    public static byte[] decrypt(String key, byte[] content) {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return cipher.doFinal(content);
    }


    /**
     * 不足16的倍数 后面补0
     *
     * @return
     * @auther sjt Administrator
     * @since 2023/12/19 20:34
     */
    public static byte[] dataSupplement(byte[] originalData) {
        int blockSize = 16;
        // 计算需要填充的字节数
        int paddingSize = blockSize - (originalData.length % blockSize);
        if (paddingSize == blockSize) {
            paddingSize = 0;  // 如果原始数据长度已经是 blockSize 的倍数，需要填充一个新的块
        }
        // 创建新的字节数组并填充
        return Arrays.copyOf(originalData, originalData.length + paddingSize);
    }
}

